import type { UploadProps } from 'ant-design-vue'
import type { FileType } from 'ant-design-vue/es/upload/interface'
import { ref } from 'vue'
import { getExtension } from '@/utils'

export function useUploadFile() {
  const fileList = ref<any[]>([])

  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    if (fileList.value.length >= 1) {
      window.$message.error('Single upload file with extensions csv or xlsx can be uploaded at a time ！')
      return
    }

    if (_validateReName(file))
      return false

    if (!_validateExeclType(file))
      return false

    fileList.value = [...fileList.value, file]
    return false
  }
  function handleRemove(file: FileType) {
    const index = fileList.value.indexOf(file)
    const newFileList = fileList.value.slice()
    newFileList.splice(index, 1)
    fileList.value = newFileList
  }
  function _validateReName(file: FileType) {
    const alreadyUpload = fileList.value.some((item: any) => {
      return item.name === file.name
    })
    if (alreadyUpload)
      window.$message.error('Do not allow submission of files with the same name ！')

    return alreadyUpload
  }

  function _validateExeclType(file: FileType) {
    const ext = getExtension(file.name)
    const isExecl = ext === 'csv' || ext === 'xls' || ext === 'xlsx'
    if (!isExecl)
      window.$message.error(`${file.name} is not a excel file`)

    return isExecl
  }

  return {
    fileList,
    beforeUpload,
    handleRemove,
  }
}
